//
//  StrategyNearbyTravelNotesViewController.m
//  ITrip
//
//  Created by 1564335 on 15-6-2.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "StrategyNearbyTravelNotesViewController.h"
#import <AFNetworking.h>
#import "URLPath.h"
#import <SDImageCache.h>
#import "StrategyAttraction_tripsParser.h"
#import "StrategyNearbyTravelNotesTableViewCell.h"
#import <MJRefresh.h>

@interface StrategyNearbyTravelNotesViewController ()<UITableViewDataSource,UITableViewDelegate, UIAlertViewDelegate>

@property(nonatomic, retain) NSMutableArray *arrayData;

@property(nonatomic, retain) UITableView *StratrgyTravelNotesVC;

@end

@implementation StrategyNearbyTravelNotesViewController

- (void)dealloc
{
    [_arrayData release];
    [_StratrgyTravelNotesVC release];
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDisk];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImage *icon = [UIImage imageNamed:@"iconfont_return"];
    icon = [icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStyleDone target:self action:@selector(getBack)];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.arrayData = [NSMutableArray array];
    
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    NSString *path = [URLPath strategyNearbyNotesURL];
    path = [path stringByAppendingFormat:@"%ld.json?attraction_trips=true&page=1", self.travelNotesId];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"attraction_trips"];
        for (NSDictionary *dic in array) {
            StrategyAttraction_tripsParser *parser = [[StrategyAttraction_tripsParser alloc] init:dic];
            [self.arrayData addObject:parser];
            [self initTableView];
            [activityIndicator stopAnimating];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 定义菊花控件
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:activityIndicator];
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = self.view.center;
    [activityIndicator release];
    [activityIndicator startAnimating];
    
    NSString *path = [URLPath strategyNearbyNotesURL];
    path = [path stringByAppendingFormat:@"%ld.json?attraction_trips=true&page=1", self.travelNotesId];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"attraction_trips"];
        for (NSDictionary *dic in array) {
            StrategyAttraction_tripsParser *parser = [[StrategyAttraction_tripsParser alloc] init:dic];
            [self.arrayData addObject:parser];
            [self initTableView];
            [activityIndicator stopAnimating];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
        [activityIndicator stopAnimating];
    }];
}

- (void)getBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initTableView
{
    self.StratrgyTravelNotesVC = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.StratrgyTravelNotesVC];
    [self.StratrgyTravelNotesVC release];
    self.StratrgyTravelNotesVC.delegate = self;
    self.StratrgyTravelNotesVC.dataSource = self;
    [self.StratrgyTravelNotesVC addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(reFresh)];
}


- (void)reFresh
{
    static NSInteger num = 2;
    NSString *path = [URLPath strategyNearbyNotesURL];
    path = [path stringByAppendingFormat:@"%ld.json?attraction_trips=true&page=%ld", self.travelNotesId, num++];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"attraction_trips"];
        for (NSDictionary *dic in array) {
            StrategyAttraction_tripsParser *parser = [[StrategyAttraction_tripsParser alloc] init:dic];
            [self.arrayData addObject:parser];
//            [[SDImageCache sharedImageCache] clearMemory];
        }
//        [[SDImageCache sharedImageCache] clearMemory];
        [self.StratrgyTravelNotesVC reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:nil delegate:self cancelButtonTitle:@"重新连接" otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    StrategyNearbyTravelNotesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[StrategyNearbyTravelNotesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        cell.contentView.frame = CGRectMake(0, 0, self.view.frame.size.width, cell.frame.size.height);
    }
    if (self.arrayData.count > indexPath.row) {
        StrategyAttraction_tripsParser *attraction_trips = [self.arrayData objectAtIndex:indexPath.row];
        cell.titleLabel.text = nil;
        cell.image_url.image = nil;
 
        for (UIView *view in cell.imageScrollView.subviews) {
            [view removeFromSuperview];
        }
        [cell setAttraction_tripsParser:attraction_trips];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
//    [[SDImageCache sharedImageCache] clearMemory];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyAttraction_tripsParser *attraction_trips = [self.arrayData objectAtIndex:indexPath.row];
    CGFloat photosWidth = 0;
    int i = 0;
    for (StrategyNotesParser *notesParser in attraction_trips.arrayData) {
        if (notesParser.photo_url != nil && ![notesParser.photo_url isEqual:[NSNull null]] && i++ < 4) {
            photosWidth += notesParser.width / (CGFloat)notesParser.height * 150;
        }
    }
    if (attraction_trips.comment != nil && ![attraction_trips.comment isEqual:[NSNull null]]) {
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:18] forKey:NSFontAttributeName];
        CGRect frame = [attraction_trips.comment boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        if (photosWidth > 0) {
            return frame.size.height + 190;
        } else {
            return frame.size.height + 40;
        }
    } else {
        if (photosWidth > 0) {
            return 190;
        } else {
            return 0;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayData.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
